package com.lyubia.shop.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.lyubia.shop.common.utils.CookieUtil;
import com.lyubia.shop.api.service.CookieService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class CookieServiceImpl implements CookieService {


    /**
     * 设置Cookie
     * @param ticket 凭证
     * @param req req
     * @param resp resp
     * @return 结果
     */
    @Override
    public boolean setCookie(String ticket, HttpServletRequest req, HttpServletResponse resp) {
        try {
            CookieUtil.setCookie(req, resp, "userTicket", ticket);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public String getCookie(HttpServletRequest req) {
        String userTicket = CookieUtil.getCookieValue(req, "userTicket");
        if (StrUtil.isEmpty(userTicket))
            throw new RuntimeException("未找到Cookie!");
        return userTicket;
    }

    @Override
    public boolean delCookie(HttpServletRequest req, HttpServletResponse resp) {
        try {
            CookieUtil.deleteCookie(req, resp, "userTicket");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
